package org.example.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.vo.Result;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/6/2
 * Email haijunzhou@hnit.edu.cn
 */
public class VcodeInterceptor implements HandlerInterceptor {

    ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String rvcode = request.getParameter("vcode");
        String svcode = (String) request.getSession().getAttribute("vcode");
        Result result;
        if(rvcode == null || rvcode.isBlank()){
            result = new Result(0,"请输入验证码!",null);
            String json = objectMapper.writeValueAsString(result);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().append(json);
            return false;
        } else if(rvcode.equalsIgnoreCase(svcode) == false){
            result = new Result(0,"请验证码输入错误!",null);
            out(result,response);
            return false;
        }
        return true;
    }

    public void out(Result result,HttpServletResponse response) throws IOException {
        String json = objectMapper.writeValueAsString(result);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().append(json);
    }

}
